package com.ad.pet.app.account.order.fragment;

import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.ad.pet.Logger;
import com.ad.pet.MainActivityCompent;
import com.ad.pet.R;
import com.ad.pet.app.Navigation;
import com.ad.pet.app.RxDisposable;
import com.ad.pet.app.account.adapter.IndoorOrderAdapter;
import com.ad.pet.common.data.http.BusCall;
import com.ad.pet.common.data.utils.ui.DialogUtil;
import com.ad.pet.common.data.utils.ui.ToastUtil;
import com.ad.pet.common.structure.events.Events;
import com.ad.pet.common.structure.events.RxBus;
import com.ad.pet.common.structure.mvp.BasePresenter;
import com.ad.pet.common.structure.ui.fragment.LoadingFragment;
import com.ad.pet.constant.Constant;
import com.ad.pet.models.remote.PayResult;
import com.ad.pet.models.remote.Wxpay;
import com.ad.pet.models.remote.account.order.BigOrder;
import com.ad.pet.models.remote.account.order.OrderType;
import com.ad.pet.ui.PayChoseDialog;
import com.ad.pet.ui.SimpleDividerDecoration;
import com.ad.pet.wxapi.PayContract;
import com.ad.pet.wxapi.PayPresenter;
import com.ad.pet.wxapi.WXPayUtils;
import com.alipay.sdk.app.PayTask;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;

import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import rx.android.schedulers.AndroidSchedulers;

/**
 * Created by SEELE on 2019/1/28.
 */

public class OrderFragment extends LoadingFragment implements OrderStatusContract.View, PayContract.View {

    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;
    @Inject
    RxDisposable mRxDisposable;
    @Inject
    OrderStatusPresenter mStatusPresenter;
    private String mStatus;
    private IndoorOrderAdapter mOrderStatusAdapter;
    @BindView(R.id.swipeRefresh)
    SwipeRefreshLayout swipeRefreshLayout;
    private int page = 1;
    private int payType;
    PayChoseDialog payChoseDialog;
    String pgid;
    static final int SDK_PAY_FLAG = 1;
    @Inject
    PayPresenter mPayPresenter;
    private Handler deliver = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG:
//                    String resault = msg.obj.toString();
//                    LogUtils.e("pay_resault",resault);
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    String notifyUrl = payResult.getNotifyUrl();
                    // 判断resultStatus 为9000则代表支付成功
                    Logger.e("result_alipay:" + resultInfo + "|" + resultStatus + "|" + notifyUrl);
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。

                        ToastUtil.getToastUtil().showShort(getString(R.string.pay_success));
                        Navigation.goServiceOrderDetail(getActivity(), pgid);
                        RxBus.getDefault().post("confim_success");
//                        finish();
//                        RxBus.getDefault().post(new Events.PayStatusCallback(notifyUrl, "alipay", resultInfo));
                    } else {//支付失败
                        ToastUtil.getToastUtil().showShort(getString(R.string.pay_failed));

                    }
                    break;
            }
        }
    };

    @Override
    protected void initData() {
        mPayPresenter.onCreate(this);
        payChoseDialog = new PayChoseDialog(getActivity(), R.style.custom_dialog_style,false);
    }

    @Override
    protected void initEvents() {
        payChoseDialog.setOnGetPayWay(new PayChoseDialog.OnGetPayWay() {
            @Override
            public void getPayWay(int way) {
                payType = way;
                mPayPresenter.upPayresult(pgid, payType != 1 ? "2" : "1");
            }
        });
        mOrderStatusAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Navigation.goServiceOrderDetail(getActivity(), mOrderStatusAdapter.getItem(position).getOrder_id());
            }
        });

        mOrderStatusAdapter.setOn0ItemClickLinstener(new IndoorOrderAdapter.OnItemClickLinstener() {
            @Override
            public void onConfirm(final int position) {
//                Navigation.goCommonWebView(getActivity(),getString(R.string.good_detail),mOrderStatusAdapter.getItem(position).getItem().get(0).getP_url(),false, MainActivity.REQUEST_GO_MALL);
                if ("0".equals(mOrderStatusAdapter.getData().get(position).getOrder_status())) {
//                    payChoseDialog.show();
                    pgid = mOrderStatusAdapter.getData().get(position).getOrder_id();
                    mPayPresenter.upPayresult(pgid, "");

                }
            }

            @Override
            public void onCancel(final int position) {
                DialogUtil.createDialog(getActivity(), "", "是否取消订单?", true, "取消", null, "确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mStatusPresenter.cancelOrder(mOrderStatusAdapter.getItem(position).getOrder_id());
                    }
                }).show();
            }
        });

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                swipeRefreshLayout.setRefreshing(true);
                mOrderStatusAdapter.setEnableLoadMore(false);
                mStatusPresenter.getOrderStatus(mStatus, String.valueOf(page));

            }
        });

        mOrderStatusAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                mStatusPresenter.getOrderStatus(mStatus, String.valueOf(++page));
            }
        }, mRecyclerView);

        mRxDisposable.add(RxBus.getDefault().toObservable(Events.PayStatusCallback.class)
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new BusCall<Events.PayStatusCallback>() {
                    @Override
                    public void call(Events.PayStatusCallback webTitle) {
                        if ("weixin_app".equals(webTitle.paytype)) {
                            RxBus.getDefault().post("confim_success");
                        }
                    }
                }));

        mRxDisposable.add(RxBus.getDefault().toObservable(String.class)
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new BusCall<String>() {
                    @Override
                    public void call(String webTitle) {
                        if ("confim_success".equals(webTitle)) {
                            page = 1;
                            mStatusPresenter.getOrderStatus(mStatus, String.valueOf(page));
                        }
                    }
                }));
    }

    @Override
    protected void initViews() {
        mStatusPresenter.onCreate(this);
        mStatus = getArguments().getString(Constant.STATUS);


        mStatusPresenter.getOrderStatus(mStatus, String.valueOf(page));

        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mOrderStatusAdapter = new IndoorOrderAdapter(null);
        mRecyclerView.addItemDecoration(new SimpleDividerDecoration(getActivity(), 9, R.color.bg_color));
        mRecyclerView.setAdapter(mOrderStatusAdapter);
        mOrderStatusAdapter.bindToRecyclerView(mRecyclerView);


    }

    @Override
    public void initInjector() {
        getComponent(MainActivityCompent.class).inject(this);
    }


    @Override
    protected int contentLayout() {
        return R.layout.fragment_order;
    }

    @Override
    protected void clickRetry(View v) {

    }

    @Override
    protected BasePresenter getPresenter() {
        return mStatusPresenter;
    }

    public static OrderFragment newInstance(String status) {
        Bundle args = new Bundle();
        OrderFragment fragment = new OrderFragment();
        args.putString(Constant.STATUS, status);

        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void error(String msg) {
        mStatusLayoutManager.showEmpty();
    }

    @Override
    public void error(int code, String msg) {
        mStatusLayoutManager.showEmpty();
    }


    @Override
    public void getPendingSuccess(List<BigOrder> bigOrder) {

    }

    @Override
    public void getPacketInfoSuccess(BigOrder bigOrder) {

    }

    @Override
    public void getOrderStatusSuccess(List<BigOrder> orderStatuses) {
        mStatusLayoutManager.showContent();
        if (swipeRefreshLayout != null) {
            swipeRefreshLayout.setRefreshing(false);
        }
        if (page == 1) {
            mOrderStatusAdapter.setNewData(orderStatuses);
        } else {
            mOrderStatusAdapter.addData(orderStatuses);
            mOrderStatusAdapter.loadMoreComplete();
        }
        if (orderStatuses.size() < 10) {//CommonConstant.PAGE_COUNT
            //暂无更多数据
            mOrderStatusAdapter.loadMoreEnd();
        }

        if (orderStatuses.size() == 0 && page == 1) {
            mOrderStatusAdapter.setEmptyView(R.layout.layout_empty_address);
            ((TextView) mOrderStatusAdapter.getEmptyView().findViewById(R.id.tv_title)).setText("您还没有相关服务哦");
//
        }

    }

    @Override
    public void cancelOrderSuccess() {
        RxBus.getDefault().post("confim_success");

        ToastUtil.getToastUtil().showShort("取消订单成功");

    }

    @Override
    public void confirmOrderSuccess() {

    }

    @Override
    public void getGoodOrderDetailSuccess(BigOrder bigOrder) {

    }

    @Override
    public void myAppointListSuccess(List<OrderType> list) {

    }

    @Override
    public void cancelAppointListSuccess() {

    }


    @Override
    public void upPayresultSuccess(PayResult payResult) {
        payType = Integer.valueOf(payResult.getPayment_type());
        if (payType == 1) {

            WXPayUtils wxPayUtils = new WXPayUtils(getActivity());
            if (wxPayUtils.isWxAppInstalledAndSupported()) {


                Wxpay wxpay = new Wxpay(payResult.getAppid(), payResult.getPartnerid(), payResult.getPrepay_id(), payResult.getNonce_str(), payResult.getTimestamp(), payResult.getPackageq(), payResult.getSign(), "notify_url");
                wxPayUtils.doPay(new Gson().toJson(wxpay));
                Logger.d("jsonString--->" + new Gson().toJson(wxpay));
            }
        } else {
            final String orderInfo = payResult.getAli_pay_str();   // 订单信息

            Runnable payRunnable = new Runnable() {

                @Override
                public void run() {
                    PayTask alipay = new PayTask(getActivity());
                    Map<String, String> result = alipay.payV2(orderInfo, false);
//                    result.put("notify_url", payUrl.getNotify_url());
                    Message msg = new Message();
                    msg.what = SDK_PAY_FLAG;
                    msg.obj = result;
                    deliver.sendMessage(msg);
                }
            };
            // 必须异步调用
            Thread payThread = new Thread(payRunnable);
            payThread.start();
        }
        payChoseDialog.dismiss();
    }
}

